8<template>
  <view class="online-reply">
    <u--form ref="form" :model="form" :rules="rules">
      <view class="reply-title">
        <view class="title">
          保修房屋
        </view>
        <view class="content">
          <u-form-item borderBottom @click="showActionSheet('选择报修房屋',repairHouseList)" prop="repairHouseTitle">
            <u--input v-model="form.repairHouseTitle" readonly placeholder="请选择报修房屋" border="none"></u--input>
            <u-icon slot="right" name="arrow-right" style="margin-right: 30px;" color="#C3C3C5"></u-icon>
          </u-form-item>
        </view>
      </view>
      <view class="reply-content">
        <view class="title">
          保修信息
        </view>
        <view class="content">
          <u-form-item label="维修项目" borderBottom labelWidth="208rpx" prop="repairItemId"
            @click="showActionSheet('选择维修项目',repairItemsList)">
            <u--input readonly placeholder="请选择"
              v-model="(repairItemsList.find(item => item.id === form.repairItemId)).name" border="none"
              placeholderStyle="color:#C3C3C5">
            </u--input>
            <u-icon slot="right" name="arrow-right" style="margin-right: 30px;" color="#C3C3C5"></u-icon>
          </u-form-item>
          <u-form-item label="手机号码" borderBottom labelWidth="208rpx" prop="mobile">
            <u--input placeholder="请输入联系电话号码" v-model="form.mobile" border="none" placeholderStyle="color:#C3C3C5">
            </u--input>
          </u-form-item>
          <u-form-item label="预约日期" borderBottom labelWidth="208rpx" prop="appointment"
            @click="dateTimePickerShow = true;lifeButtonShow = false">
            <u--input readonly placeholder="请选择上门维修日期" v-model="form.appointment" border="none"
              placeholderStyle="color:#C3C3C5">
            </u--input>
            <u-icon slot="right" name="arrow-right" color="#C3C3C5"></u-icon>
          </u-form-item>
          <u-form-item borderBottom prop="description">
            <view class="label-input">
              <u-cell-group :border="false">
                <u-cell :border="false" title="问题描述">
                  <view slot="label">
                    <u--textarea v-model="form.description" height="84rpx" placeholder="请填写详细报修内容，有助于工作人员快速帮您解决问题。"
                      border="none">
                    </u--textarea>
                  </view>
                </u-cell>
              </u-cell-group>
            </view>
          </u-form-item>
          <u-form-item borderBottom>
            <view class="label-input label-upload">
              <u-cell-group :border="false">
                <u-cell :border="false" title="问题附件">
                  <view slot="label">
                    <u-upload v-if="isShowUploadBoxs" @afterRead="afterRead" @delete="deletePic" uploadIcon="plus"
                      uploadIconColor="#c5c5c7" :fileList="fileList1" multiple name="1" multiple :maxCount="9"
                      width="154rpx" height="154rpx">
                    </u-upload>
                  </view>
                </u-cell>
              </u-cell-group>
            </view>
          </u-form-item>
        </view>
      </view>
      <!-- 选择维修项目 -->
      <u-action-sheet :round="10" @close="lifeButtonShow = true;repairHouseShow = false;" :closeOnClickAction="true"
        :closeOnClickOverlay="true" @select="selectClick" :actions="list" :title="actionSheetTitle"
        :show="repairHouseShow" cancelText="取消">
      </u-action-sheet>
      <!-- 选择日期 -->
      <u-datetime-picker :closeOnClickOverlay="true" ref="datetimePicker" :show="dateTimePickerShow"
        v-model="dateTimePickerVal" mode="date" :formatter="formatter" @confirm="dateTimePickerConfirm"
        @cancel="lifeButtonShow = true;dateTimePickerShow=false;" @close="dateTimePickerShow=false">
      </u-datetime-picker>
      <!-- 提交保修 -->
      <life-button @click="onWarranty" v-if="lifeButtonShow" icon="../../static/icon/repair.png"
        :title="id?'修改报修房屋':'提交审核'"></life-button>
    </u--form>
  </view>
</template>

<script>
  import {
    getRepairHouseList,
    getRepairItems,
    toRepair,
    getUpload,
    getRepairDetail
  } from '../../api/repair.js'
  export default {
    data() {
      return {
        id: '',
        isShowUploadBoxs: false,
        actionSheetTitle: '',
        repairItemId: '请选择',
        appointment: '请选择上门维修日期',
        repairItemsList: [],
        lifeButtonShow: true,
        fileList1: [],
        dateTimePickerVal: Number(new Date()),
        dateTimePickerShow: false,
        repairHouseList: [],
        repairHouseShow: false,
        repairItem: '',
        // 表单
        form: {
          repairHouseTitle: '',
          houseId: '',
          repairItemId: '',
          mobile: '',
          description: '',
          attachment: [],
          appointment: ''
        },
        // 校验规则
        rules: {
          repairHouseTitle: {
            required: true,
            message: '请选择报修房屋',
            trigger: ['change', 'blur']
          },
          mobile: [{
              required: true,
              message: '请输入手机号',
              trigger: ['change', 'blur'],
            },
            {
              pattern: /^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/,
              message: '手机号码格式不正确',
              trigger: ['change', 'blur'],
            }
          ],
          appointment: {
            required: true,
            message: '请选择上门维修日期',
            trigger: ['change', 'blur']
          },
          repairItemId: {
            required: true,
            message: '请选择维修项目',
            trigger: ['change', 'blur']
          },
          description: {
            required: true,
            message: '请输入问题描述',
            trigger: ['change', 'blur']
          }
        },
        // actionSheet列表
        list: []
      }
    },
    methods: {
      async getRepairDetail(id) {
        const {
          data: {
            houseInfo,
            houseId,
            repairItemId,
            mobile,
            description,
            appointment,
            attachment
          }
        } = await getRepairDetail(id)
        this.form.repairHouseTitle = houseInfo
        this.form.houseId = houseId
        this.form.repairItemId = repairItemId
        this.form.mobile = mobile
        this.form.description = description
        this.form.appointment = appointment
        attachment.forEach((item, index) => {
          this.afterRead({
            name: '1',
            index: index,
            file: {
              type: "image",
              url: item.url,
              thumb: item.url
            }
          })
        })
      },
      // 提交保修
      async onWarranty() {
        try {
          await this.$refs.form.validate()
          if (!this.form.attachment.length) {
            return uni.showToast({
              title: '请上传问题附件',
              icon: 'error'
            })
          }
          await toRepair(this.form)
          uni.switchTab({
            url: '/pkg-reply/my-repair/my-repair'
          })
        } catch (e) {
          console.log(e);
          //TODO handle the exception
        }
      },
      // 打开actionSheet
      showActionSheet(str, arr) {
        this.actionSheetTitle = str
        this.list = arr
        this.lifeButtonShow = false
        this.repairHouseShow = true
      },
      // 获取维修项
      async getRepairItems() {
        const {
          data
        } = await getRepairItems()
        this.repairItemsList = data
      },
      // 选择维修项
      selectClick(index) {
        console.log(this.actionSheetTitle)
        if (this.actionSheetTitle === '选择报修房屋') {
          // 报修房屋
          this.form.houseId = index.id
          this.form.repairHouseTitle = index.name
        } else {
          // 报修项目
          this.form.repairItemId = index.id
        }
        this.repairHouseShow = false
      },
      // 获取我能报修的房屋
      async getRepairHouseList() {
        const {
          data
        } = await getRepairHouseList()
        this.repairHouseList = data
      },
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },
      // 上传图片
      async afterRead(e) {
        let lists = [].concat(e.file)
        let fileListLen = this[`fileList${e.name}`].length
        lists.map((item) => {
          this[`fileList${e.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url, e.name)
          let item = this[`fileList${e.name}`][fileListLen]
          this[`fileList${e.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))
          fileListLen++
          this.isShowUploadBoxs = true
        }
      },
      // 上传回调
      FilePromise(locationUrl, header, num) {
        console.log('开始上传');
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: 'https://live-api.itheima.net/upload', // 仅为示例，非真实的接口地址
            filePath: locationUrl,
            header: header,
            name: 'file',
            formData: {
              file: locationUrl
            },
            success: (res) => {
              const res1 = JSON.parse(res.data)
              console.log('上传成功');
              resolve(res1.data)
              if (num === '1') {
                this.form.idcardBackUrl = res1.data.url
              } else {
                this.form.idcardFrontUrl = res1.data.url
              }
            }
          });
        })
      },
      // 上传图片
      async uploadFilePromise(url, num) {
        const token = this.$store.state.user.userToken.token
        const header = {
          Authorization: 'Bearer ' + token
        }
        if (this.id) {
          let locationUrl = url
          await uni.downloadFile({
            url: locationUrl,
            success: (res2) => {
              if (res2.statusCode === 200) {
                console.log('下载成功');
                locationUrl = res2.tempFilePath
                return this.FilePromise(locationUrl, header, num)
              }
            }
          })
        } else {
          return this.FilePromise(url, header, num)
        }
      },
      // 确认按钮dateTimePicker
      dateTimePickerConfirm(e) {
        this.form.appointment = this.$options.filters['formatTime'](e.value)
        this.dateTimePickerShow = false
        this.lifeButtonShow = true
      },
      formatter(type, value) {
        if (type === 'year') {
          return `${value}年`
        }
        if (type === 'month') {
          return `${value}月`
        }
        if (type === 'day') {
          return `${value}日`
        }
        return value
      },
    },
    onLoad(options) {
      if (options.id) {
        this.id = options.id
        this.getRepairDetail(options.id)
        this.buttonIcon = '../../static/icon/revise.png'
        uni.setNavigationBarTitle({
          title: '报修详情'
        })
      } else {
        this.isShowUploadBoxs = true
      }
      this.getRepairHouseList()
      this.getRepairItems()
    },
    onReady() {
      // 微信小程序需要用此写法
      this.$refs.datetimePicker.setFormatter(this.formatter)
      this.$refs.form.setRules(this.rules)
    },
  }
</script>

<style lang="scss">
  .online-reply {
    height: 100%;
    background-color: #FAFAFA;
    padding-bottom: 213rpx;
    overflow: hidden;

    .reply-title {
      .title {
        padding: 30rpx;
        color: #979797;
        font-size: 24rpx;

      }

      .content {
        color: #333333;
        font-size: 28rpx;
        line-height: 1.5;
        letter-spacing: 0rpx;
        background-color: #fff;

        ::v-deep .u-form-item__body {
          padding: 30rpx;
        }
      }
    }

    .reply-content {
      .title {
        padding: 30rpx;
        color: #979797;
        font-size: 24rpx;

      }

      .content {
        background-color: #fff;
        // overflow: hidden;
        padding: 0 0 0 30rpx;

        ::v-deep .item__body__right__content__icon {
          margin-right: 30rpx;
        }

        ::v-deep .u-cell__body {
          padding: 0rpx !important;
        }

        ::v-deep .u-upload__button {
          background-color: #fff;
          border: 1rpx solid #F2F2F6;
        }

        ::v-deep .u-textarea {
          padding-right: 28rpx !important;
        }

        // .mobileInput {
        //   position: relative;
        //   left: 28rpx;
        // }

        .label-upload {
          overflow: hidden;

          ::v-deep .u-cell__title-text {
            margin-bottom: 20rpx;
          }
        }

        ::v-deep .label-input {
          overflow: hidden;

          .u-cell__body {
            padding: 0rpx;
            padding-right: 15rpx;
          }

          .u-textarea {
            padding: 0rpx;
            margin-top: 20rpx;
          }
        }

      }
    }
  }
</style>
